<template>
    <div class="container banner-add-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <!-- 赞助商设置 -->
            <div class="form-unit">
                <div class="form-title">banner位设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="title"
                    label="banner名称:"
                >
                    <el-input
                        placeholder="必填"
                        v-model="formData.title"
                        size="small"
                        class="task-input"/>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="image_url"
                    label="banner图片:"
                >
                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*"
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="formData.image_url"
                            :src="formData.image_url"
                            class="avatar">
                        <i
                            class="el-icon-upload"
                            v-if="!formData.image_url"/>
                        <div
                            class="el-upload__text"
                            v-if="!formData.image_url">将文件拖到此处，或<em>点击上传</em></div>
                        <div
                            class="el-upload__tip"
                            slot="tip">
                            只能上传jpg/png文件，且不超过500kb，banner尺寸:710*200
                        </div>
                    </el-upload>
                </el-form-item>
                <!-- banner跳转 -->
                <el-row class='row-flex'>
                    <el-form-item
                        class="task-form-item"
                        size="small"
                        label="跳转链接:"
                        prop="app_action"
                    >
                        <el-cascader
                            :props="{ expandTrigger: 'hover' }"
                            :placeholder="setJump"
                            size="small"
                            :filterable="true"
                            v-model="formData.app_action"
                            :options="linkSelectData"
                            @change="handleChange()"
                            ref="myCascader"
                            style="width:435px"
                        />
                    </el-form-item>
                </el-row>
                <el-form-item
                    size="small"
                >
                    <!-- 外链输入框 -->
                    <div
                        v-for="(item,index) in param"
                        :key="index"
                    >
                        <div v-if="item.type == 'text'">
                            <el-input
                                placeholder="请输入链接"
                                style="width: 300px"
                                v-model="formData.jump_url"
                                @input="getJump"
                                clearable
                            >
                                <template
                                    class="param"
                                    slot="prepend">{{ item.title }}</template>
                            </el-input>
                            <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                        </div>
                    </div>
                    <!-- 外链输入框 -->

                    <!-- 内链选择框 -->
                    <el-form-item
                        size="small"
                    >
                        <div
                            v-for="(item,index) in paramCont"
                            :key="index"
                        >
                            <div
                                v-if="paramCont.length == 2 "
                                style="display:flex;marginBottom: 10px"
                            >
                                <p class="el-select-title">{{ item.title }}</p>
                                <el-select
                                    v-model="list[index]"
                                    filterable
                                    placeholder="请选择"
                                    @change="getLink"
                                    style="marginLeft: -5px;width:239px"
                                >
                                    <el-option
                                        v-for="item in options[index]"
                                        :key="item.value"
                                        :label="item.title"
                                        :value="item.value"/>
                                </el-select>
                                <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                            </div>
                            <div
                                v-if="item.type == 'select' && paramCont.length == 1 "
                                style="display:flex;marginBottom: 10px"
                            >
                                <p class="el-select-title">{{ item.title }}</p>
                                <el-select
                                    v-model="formData.jump_url"
                                    filterable
                                    placeholder="请选择"
                                    @change="getJump"
                                    style="marginLeft: -5px;width:239px"
                                >
                                    <el-option
                                        v-for="item in options[index]"
                                        :key="item.value"
                                        :label="item.title"
                                        :value="item.value"/>
                                </el-select>
                                <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                            </div>
                            <div v-if="item.type == 'text'">
                                <el-input
                                    placeholder="请输入链接"
                                    style="width: 300px"
                                    v-model="formData.jump_url"
                                    @input="getJump"
                                    clearable
                                >
                                    <template
                                        class="param"
                                        slot="prepend">{{ item.title }}</template>
                                </el-input>
                                <p style="display:inline-block;color:#999;margin-left:12px">*需要联系技术提供</p>
                            </div>
                        </div>
                    </el-form-item>
                    <!-- 内链输入框 -->
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="showTime"
                    label="展示时间:">
                    <el-date-picker
                        v-model="formData.showTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    label="上架状态:">
                    <el-switch
                        v-model="formData.status"
                        active-color="#13ce66"
                        active-text="上架"
                        :active-value="1"
                        :inactive-value="0"
                        inactive-text="下架"/>
                </el-form-item>
                <!-- banner跳转 -->
                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="type"
                    label="作用域:"
                >
                    <el-radio-group
                        v-model="formData.type"
                        @change="fnGetFormType"
                    >
                        <el-radio
                            :label="1"
                            :value="1">学习</el-radio>
                        <el-radio
                            :label="2"
                            :value="2">工作</el-radio>
                        <el-radio
                            :label="6"
                            :value="6">商城</el-radio>
                        <el-radio
                            :label="7"
                            :value="7">商品组</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item
                    label="商城金刚区"
                    prop="type_param"
                    v-if="isType"
                >
                    <el-select
                        v-model="formData.type_param"
                        filterable
                        placeholder="请选择"
                        size="small"
                        @change="fnSetTypeParam"
                    >
                        <el-option
                            v-for="item in shopList"
                            :key="item.cate_no"
                            :label="item.cate_name"
                            :value="item.cate_no"
                        />
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="sort"
                    label="排序:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.sort"
                        size="small"
                        prop="sort"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*数字越小排名越靠前</span>
                </el-form-item> -->

                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    label="状态展示:">
                    <el-switch
                        v-model="formData.status"
                        active-color="#13ce66"
                        active-text="展示"
                        :active-value="1"
                        :inactive-value="0"
                        inactive-text="隐藏"/>
                </el-form-item> -->
                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    label="学校权限设置:">
                    <el-switch
                        v-model="formData.school_filter_status"
                        active-color="#13ce66"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </el-form-item> -->
                <!-- <el-form-item
                    class="task-form-item"
                    size="small"
                    label="添加学校:"
                >
                    <div
                        class="el-tag-school"
                        v-if="selectedSchools.length > 0"
                    >
                        <el-tag
                            :key="tag"
                            v-for="tag in selectedSchools"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)"
                        >
                            {{ JSON.parse(tag).name }}
                        </el-tag>
                        <i
                            class="el-icon-circle-plus-outline"
                            @click="showChooseSchool = true"
                        />
                    </div>
                    <i
                        v-if="selectedSchools.length == 0"
                        class="el-icon-circle-plus-outline"
                        @click="showChooseSchool = true"
                    />
                </el-form-item> -->
            </div>
            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        v-show="banner_id ? false : true"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
        <!-- 选择学校 -->
        <el-dialog
            title="选择学校"
            width="1048px"
            custom-class="choose-dialog"
            :visible.sync="showChooseSchool"
        >
            <el-cascader
                v-model="selectedCity"
                placeholder="请选择城市"
                :options="cities"
                :props="props"
                filterable
                size="small"
                style="width: 120px;marginBottom:15px"
                @change="fnChangeCity"
            />
            <el-input
                placeholder="请输入搜索内容"
                v-model.trim="searchKey"
                size="small"
                style="width: 380px"
                @keyup.native.enter="fnSearchSchool()"
            >
                <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="fnSearchSchool()"
                />
            </el-input>
            <div class="el-tag-school">
                <el-tag
                    :key="tag"
                    v-for="tag in selectedSchools"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                >
                    {{ JSON.parse(tag).name }}
                </el-tag>
            </div>
            <div class="splider" />
            <div class="school-list">
                <div
                    class="empty"
                    v-if="schoolList.length <= 0"
                >
                    请切换城市
                </div>
                <el-checkbox-group
                    v-model="selectedSchools"
                    size="small"
                    v-else
                >
                    <el-checkbox-button
                        v-for="(school, schoolIndex) in schoolList"
                        :label="JSON.stringify({
                            id: school.id,
                            name: school.name
                        })"
                        :key="schoolIndex"
                    >{{ school.name }}</el-checkbox-button>
                </el-checkbox-group>
            </div>
            <el-button
                type="primary"
                size="small"
                class="submit-btn"
                @click="showChooseSchool = false"
            >确定</el-button>
        </el-dialog>
        <!-- 选择学校 -->
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        var validateLinkUrl = (rule, val, callback) => {

            if(val.indexOf('http://') == -1){
                callback(new Error('错误'));
                return;
            }
            callback();
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        return {
            status: false,
            isType: false,
            shopList: [],
            prevPage: '',
            checkList: [1, 2],
            authResult: {},
            breadcrumbList: [{title: "APP后台",},{title: "商城"},{title: '页面中的banner位'}],
            link_text: '',
            banner_id: '',
            provence: [],
            linkSelectData: [],
            param: [],
            paramCont: [],
            isapp: true,
            setJump: '请选择',
            ifSelect: '',
            action: '',
            options: [],
            type_param: {},
            formData: {
                title: "",
                image_url: '',
                app_action: '',
                jump_url: '',
                type: 1,
                start_time: 0,
                end_time: 0,
                showTime: [this.fnInitTimeNow(), ''],
                status: 1,
                type_param: '',
                form_name: '',
                school_filter_status: ''
            },
            // 添加学校权限
            showChooseSchool: false,
            selectedCity: [],
            cities: [],
            searchKey: '',
            // 弹窗当前显示学校集合
            schoolList: [],
            // 当前选中的学校
            selectedSchools: [],
            //所有学校集合
            city_schools: {},
            props: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            //
            list: [],
            formRule: {
                title: [
                    { required: true, message: '请填写banner名称,不可以为空', trigger: 'change' }
                ],
                jump_url: [
                    { required: true, message: '请输入跳转链接', trigger: 'blur' },
                ],
                image_url: [
                    { required: true, message: 'banner位图片不能为空', trigger: 'change' }
                ],
                // type: [
                //     { required: true, message: '请选择作用域', trigger: 'change' }
                // ],
                showTime: [
                    { required: true, message: '请填写展示时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的时间', trigger: 'blur' }
                ],
                // sort: [
                //     { required: true, message: '请填写排序', trigger: 'blur' }
                // ],
                app_action: [
                    { required: true, message: '跳转链接不能为空', trigger: 'change' }
                ],
                type_param: [
                    { required: true, message: '请选择跳转链接', trigger: 'blur' }
                ]
            },
            submitting: false,
            init: false,
            baseUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.fnGetSchoolList();
        this.getParam();
        this.getappAcion();
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);
        this.getList();
        if (!this.banner_id) {
            this.init = true;
        } else {
            this.fnInitBannerInfo();
        }
    },
    computed: {
        selectedSchoolObjs() {
            let res = [];

            this.selectedSchools.forEach((item) => {
                /* eslint-disable */
          outer:
          for (let i in this.city_schools) {
            for (let j in this.city_schools[i]) {
              if (this.city_schools[i][j].id == item) {
                res.push(this.city_schools[i][j]);
                break outer;
              }
            }
          }
          /* eslint-enable */
            });
            return res;
        },
    },
    mounted () {
        if (window.history && window.history.pushState && this.prevPage !== '') {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goBack, false);
        }

        if(this.$route.query.status) {
            this.status = this.$route.query.status;
        }
    },
    destroyed(){
        if (this.prevPage !== '') {
            window.removeEventListener('popstate', this.goBack, false);
        }
    },
    methods: {
        /**
         * 学校权限
         */
        fnChangeCity() {
            if (this.selectedCity.length >= 2) {
                this.schoolList = this.city_schools['city_' + this.selectedCity[1]];
                this.searchKey = '';
            } else {
                this.schoolList = [];
                this.searchKey = '';
            }
        },
        fnSearchSchool() {
            if (this.selectedCity.length >= 2) {
                this.schoolList = this.city_schools['city_' + this.selectedCity[1]].filter(item => {
                    if (!this.searchKey) {
                        return true;
                    }
                    return item.name.indexOf(this.searchKey) > -1;
                });
            } else {
                this.schoolList = [];
            }
        },
        fnGetSchoolList() {
            this.$post('/student/local_info%5Cschool_tree', {
            }, resp => {
                if (resp.code == 1) {
                    // 将学校与省市剥离,方便显示以及遍历
                    let tree = resp.data.tree;
                    let cityTmp = [];
                    let schoolTmp = {};

                    tree.forEach(item => {
                        let provinceTmp = {
                            id: item.id,
                            name: item.name,
                            children: []
                        };

                        if (item.children) {
                            item.children.forEach((city) => {
                                provinceTmp.children.push({
                                    id: city.id,
                                    name: city.name
                                });
                                schoolTmp['city_' + city.id] = city.children;
                            });
                        }
                        cityTmp.push(provinceTmp);
                    });

                    this.cities = cityTmp;
                    this.city_schools = schoolTmp;
                    this.selectedCity = [12, 88];
                    this.fnChangeCity();
                }
            });
        },

        /**
         * 移除学校
         */
        handleClose (tag) {
            this.selectedSchools.splice(this.selectedSchools.indexOf(tag), 1);
        },

        /**
         * 获取url参数
         */
        getParam () {
            let query = this.$route.query;

            if (query.page !== undefined || query.banner_id !== undefined) {
                this.prevPage = query.page;
                this.banner_id = query.banner_id;
            }
        },

        /**
         * 监听返回事件
         */
        goBack () {
            if (this.prevPage !== '') {
                this.$router.replace({
                    name: 'shopBanner',
                    query: {
                        page: this.prevPage
                    }
                });
            }
        },

        /**
         * 获取金刚区分类列表
         */
        getList () {
            this.$post('/student/shop_goods_cate%5Cget_list_select',{},resp=>{
                if (resp.code == 1) {
                    this.shopList = resp.data.list;
                }
            });
        },

        /**
         * 作用域
         */
        fnGetFormType (event) {
            if (Number(event) == 7) {
                this.isType = true;
            } else {
                this.isType = false;
            }
        },

        /**
         * 设置参数
         */
        fnSetTypeParam () {
            this.type_param = {
                cate_no: this.formData.type_param
            };
        },

        /**
         * app行为数据处理
         */
        getappAcion () {
            let arr = [];
            let param = '';
            let val = '';

            this.$post('/student/app_action%5Cget_cascade_list', {
            }, resp => {
                if (resp.code == 1) {
                    resp.data.list.map((item,index)=>{
                        arr.push({
                            value: item.action,
                            label: item.title,
                            children: []
                        });
                        item.target_list.map((itm, idx) => {
                            val = {
                                target: itm.target,
                                param: []
                            };
                            itm.param_list.map((option,i)=> {
                                val.param.push({
                                    param: option.param,
                                    title: option.title,
                                    type: option.form_type
                                });
                            });
                            arr[index].children.push({
                                value: JSON.stringify(val),
                                label: itm.title
                            });
                        });
                    });
                }
                this.linkSelectData = arr;

                //提交数据类型
                // {"action":"link_outer","target":"jump","param":{"url":"11"}}
                // {"action":"app_page","target":"custom_form_custom_scene","param":{"form_no":"fm_72e0ab2ce6c04","scene_key":"222"}}
            });
        },
        /**
         * app链接数据处理
         */
        handleChange () {
            let app_action = this.formData.app_action;
            let obj = JSON.parse(app_action[1]);
            let link = {
                action: '',
                target: '',
                param: {}
            };
            let param = [];

            // console.log(app_action, 'app_action');

            this.formData.form_name = '';
            this.$set(this.formData, 'jump_url', '');

            if (app_action[0] == 'app_page') { //内部链接
                let param_list = obj.param;

                this.param = this.paramCont = this.list = [];

                if (param_list.length == 1) {
                    for(let i in param_list) {
                        param.push(
                            param_list[i]
                        );
                    }
                    this.list = [''];
                } else if (param_list.length == 2) {
                    param_list.map(item=>{
                        param.push({
                            type: 'select',
                            param: item.param,
                            title: item.title,
                            target: obj['target']
                        });
                    });
                    this.list = ['',''];
                }

                this.paramCont = param;

                if (this.paramCont.length == 0) {
                    this.link = {
                        action: app_action[0],
                        target: JSON.parse(app_action[1]).target,
                        param: {}
                    };
                    return;
                }

                this.options = [];
                this.paramCont.map((item,index)=>{
                    if (item.type == 'select') {
                        this.$post('/student/app_action%5Cget_param_item_list',{
                            action: 'app_page',
                            target: obj['target'],
                            param: item.param
                        },resp => {
                            if (resp.code == 1 ) {
                                if (this.paramCont.length == 1) {
                                    this.options.push(
                                        resp.data.list
                                    );
                                } else if (this.paramCont.length == 2){ // 设置顺序
                                    if (item.param == 'form_no') {
                                        this.options.push(
                                            resp.data.list
                                        );
                                    }
                                    if (item.param == 'scene_key') {
                                        setTimeout(()=>{
                                            this.options.push(
                                                resp.data.list
                                            );
                                        },200);
                                    }
                                }
                            } else if (resp.code == 0) {
                                this.options = [];
                            }
                        });
                        link.param[[item['param']]] = this.formData.jump_url;
                    }
                    if (item.type == 'text') {
                        link.param[[item['param']]] = this.formData.form_name;
                    }

                    link.action = app_action[0];
                    link.target = obj['target'];
                });
            } else if (app_action[0] == 'link_outer') { //外部链接
                this.paramCont = [];
                this.ifSelect = 'text';
                this.param = obj.param;

                //链接赋值
                link = {
                    action: app_action[0],
                    target: obj['target'],
                    param: {
                        url : this.formData.jump_url
                    }
                };
            } else {
                return;
            }
            this.link = link;

            // console.log(this.link, '111');
        },

        /**
         * @abstract  单链接text_select处理
         */
        getJump (url) {
            let param = {};

            this.$set(this.formData, 'jump_url', url);
            for(let key in this.link['param']) {
                param[key] = url;
            }

            this.link['param'] = param;
            console.log(JSON.stringify(this.link), 'app_action');
        },

        /**
         * @abstract  双链接select处理
         */
        getLink () {
            let param = {};

            //保证param字段不重复，否则值会被覆盖
            this.paramCont.map((item,index)=>{
                param[item.param] = this.list[index];
            });

            this.link['param'] = param;
            console.log(JSON.stringify(this.link), 'app_action');
        },

        /**
         * banner数据回显处理
         */
        fnInitBannerInfo() {
            this.$post('/student/shop_banner%5Cget', {
                banner_no: this.banner_id
            }, resp => {
                if(resp.code == 1){
                    let bannerList = resp.data;

                    if (resp.data.app_action == '') {
                        this.formData = {
                            ...bannerList,
                            showTime: [new Date(bannerList.start_time * 1000), new Date(bannerList.end_time * 1000)],
                            app_action: ''
                        };
                        this.init = true;
                        return;
                    } else {
                        this.formData = {
                            create_time: bannerList.create_time,
                            end_time: bannerList.end_time,
                            image_url: bannerList.image_url,
                            // sort: bannerList.sort,
                            start_time: bannerList.start_time,
                            status: bannerList.status,
                            title: bannerList.title,
                            // type: bannerList.type,
                            // type_param: bannerList.type_param['cate_no'],
                            // school_filter_status: bannerList.school_filter_status,
                            showTime: [new Date(bannerList.start_time * 1000), new Date(bannerList.end_time * 1000)]
                        };
                        // if (Number(this.formData.type) == 7) {
                        //     this.isType = true;
                        // }
                    }

                    //  学校权限回流
                    // this.setSchool_ids(bannerList.school_filter_school_ids);

                    //  跳转链接回流
                    if (resp.data.app_action == '') {
                        return;
                    }

                    if(JSON.stringify(JSON.parse(resp.data.app_action).param) == '{}') {
                        this.setUrlData(JSON.parse(resp.data.app_action));
                        this.init = true;
                        return;
                    }

                    let app_action = JSON.parse(resp.data.app_action);
                    let app = [];

                    this.$post('/student/app_action%5Cget_cascade_list', {}, resp => {
                        if (resp.code == 1) {
                            resp.data.list.map(item => {
                                if (app_action.action == 'link_outer') {
                                    item.target_list.map(itm => {
                                        if (itm.target == app_action.target) {
                                            app.push(
                                                app_action.action,
                                                JSON.stringify({
                                                    target: app_action.target,
                                                    param: [{
                                                        param: itm.param_list[0].param,
                                                        title: itm.param_list[0].title,
                                                        type: itm.param_list[0].form_type
                                                    }]
                                                })
                                            );
                                            this.setApp_action(app,itm.param_list[0].title,app_action.param.url,itm.target);
                                        }
                                    });
                                }

                                if (app_action.action == 'app_page') {
                                    let length = Object.keys(app_action.param).length;

                                    app = [];
                                    app.push(
                                        app_action.action,{
                                            target: app_action.target,
                                            param: []
                                        }
                                    );
                                    item.target_list.map((itm,idx) => {
                                        if (itm.target == app_action.target) {
                                            itm.param_list.map((option,i) => {
                                                app[1].param.push({
                                                    param: option.param,
                                                    title: option.title,
                                                    type: option.form_type
                                                });
                                            });
                                        }
                                    });
                                    setTimeout(()=>{
                                        if (this.isapp) {
                                            this.setSelect_action(app,length,app_action.param);
                                            this.isapp = false;
                                        }
                                    },50);
                                } else {
                                    return;
                                }
                            });
                        }
                    });
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * param空回填
         */
        setUrlData (url) {
            this.paramCont = [];
            this.formData.app_action = [
                "app_page",
                JSON.stringify({
                    target : url.target,
                    param: []
                })
            ];
            this.link = {
                action :"app_page",
                target : url.target,
                param: {}
            };
        },

        /**
         * 学校过滤
         */
        setSchool_ids (ids) {
            let school = [];

            setTimeout(()=> {
                ids.map(item => {
                    this.schoolList.map(option => {
                        if (item == option.id) {
                            school.push(JSON.stringify({
                                id: option.id,
                                name: option.name
                            }));
                        }
                    });
                });
                this.selectedSchools = school;
            },1000);
        },

        /**
         * select
         */
        setSelect_action (app,length,url) {
            if (length == 1) {
                let list = JSON.parse(JSON.stringify(app));
                let param = JSON.stringify(app[1]);

                this.paramCont = [{
                    type: list[1].param[0]['type'],
                    title: list[1].param[0]['title']
                }];
                list[1] = param;
                this.formData.app_action = list;
                this.options = [];

                for(let i in url) {
                    if(this.paramCont[0].type == 'select') {
                        this.$post('/student/app_action%5Cget_param_item_list',{
                            action: 'app_page',
                            target: JSON.parse(list[1]).target,
                            param: i
                        },resp => {
                            if (resp.code == 1 ) {
                                this.options.push(
                                    resp.data.list
                                );
                            } else if (resp.code == 0) {
                                this.options = [];
                            }
                        });
                    }

                    this.$set(this.formData, 'jump_url', url[i]);
                    this.link = {
                        "action":"app_page",
                        "target": JSON.parse(list[1]).target,
                        "param":{
                            [i]: url[i]
                        }
                    };
                    console.log(this.link, 'aa');
                }
            } else if (length == 2) {
                let data = JSON.parse(JSON.stringify(app));
                let params = JSON.stringify(app[1]);
                let current = [];

                app[1] = params;
                this.formData.app_action = app;
                this.paramCont = [];
                this.list = [];

                if (typeof(data[1].param) == 'object') {
                    data[1].param.map((item,index)=>{
                        this.paramCont.push({
                            type: 'select',
                            title: data[1].param[index]['title'],
                            param: item.param,
                            target: data[1].target
                        });
                    });
                }

                this.options = [];
                for(let i in url) {
                    this.$post('/student/app_action%5Cget_param_item_list',{
                        action: 'app_page',
                        target: data[1].target,
                        param: i
                    },resp => {
                        if (resp.code == 1 ) {
                            if (i == 'form_no') {
                                this.options.push(
                                    resp.data.list,
                                );
                            }
                            if (i == 'scene_key') {
                                setTimeout(()=>{
                                    this.options.push(
                                        resp.data.list,
                                    );
                                },150);
                            }
                        } else if (resp.code == 0) {
                            this.options = [];
                        }
                    });
                    this.link = {
                        action :"app_page",
                        target : data[1].target,
                        param: url
                    };
                    this.list.push(url[i]);
                }
            }
            this.init = true;
        },

        /**
         * link_outer
         */
        setApp_action (app,title,url,target) {
            this.formData.app_action = app;
            this.$set(this.formData, 'jump_url', url);
            this.param = [{
                type: 'text',
                title: title
            }];
            this.link = {"action":"link_outer","target":target,"param":{"url":url}};
            this.init = true;
        },
        // {"action":"app_page","target":"custom_form_custom_scene","param":{"form_no":"fm_5507cab254059","scene_key":"掌大精英可见"}}

        fnInitTimeNow() {
            var timestamp=new Date().getTime();

            return timestamp;
        },

        fnAreaLimitChange() {
            this.formData.limit_pids = [];
        },

        /**
         * 表单提交
         */
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.formData.intro = this.$refs.ueditor ? this.$refs.ueditor.getUEContent() : '';
            this.$refs.mainform.validate(valid => {
                if(valid){
                    if (this.paramCont.length == 2) {
                        if (this.list[0] == '') {
                            this.$message({
                                type: 'waring',
                                message: '表单不可以为空',
                                center: true
                            });
                            return;
                        } else if (this.list[1] == '') {
                            this.$message({
                                type: 'waring',
                                message: '场景不可以为空',
                                center: true
                            });
                            return;
                        }
                    } else if (this.paramCont.length !== 2) {
                        // if (this.formData.jump_url == '') {
                        //     this.$message({
                        //         type: 'waring',
                        //         message: '链接不可以为空',
                        //         center: true
                        //     });
                        //     return;
                        // }
                    }
                    this.submitting = true;

                    if (this.link == '') {
                        this.handleChange();
                    }

                    let school_filter_school_ids = [];

                    if (Object.keys(this.selectedSchools).length >= 1 ) {
                        this.selectedSchools.map(item=>{
                            school_filter_school_ids.push(
                                JSON.parse(item).id
                            );
                        });
                    }

                    let data = {
                        title: this.formData.title,
                        image_url: this.formData.image_url,
                        // jump_url: this.formData.jump_url,
                        // type_param: this.formData.type == 7 ?JSON.stringify({
                        //     cate_no: this.formData.type_param
                        // }) : '',
                        // type : this.formData.type,
                        start_time: Date.parse(this.formData.showTime[0])/1000,
                        end_time : Date.parse(this.formData.showTime[1])/1000,
                        // sort: this.formData.sort,
                        status: this.formData.status,
                        app_action: JSON.stringify(this.link),
                        // school_filter_status: this.formData.school_filter_status,
                        // school_filter_school_ids: school_filter_school_ids.length > 0 ? school_filter_school_ids.join() : ''
                    };

                    // console.log(data, 'data');

                    if(this.banner_id){
                        this.$post('/student/shop_banner%5Cset', {
                            banner_no: this.banner_id,
                            title: data.title,
                            image_url: data.image_url,
                            app_action: data.app_action,
                            start_time: data.start_time,
                            end_time: data.end_time,
                            status: data.status
                        }, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                this.goBack();
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/student/shop_banner%5Cadd', {
                            title: data.title,
                            image_url: data.image_url,
                            app_action: data.app_action,
                            start_time: data.start_time,
                            end_time: data.end_time,
                            status: data.status
                        }, resp => {
                            if(resp.code == 1){
                                this.banner_id = resp.data.banner_no;
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.goBack();
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }
                }
            });
        },
        /** 数组中删除某个元素 */
        fndeleteItem(list, index, bind) {
            list.splice(index, 1);
            this[bind] = list.length;
        },
        /** 上传组件回调 文件队列修改 */
        fnUploadChange(file, item) {
            item.preview_url = file.url;
        },
        fnBeforeUpload(file, item){
            item.status = 'uploading';
        },
        /** 上传组件回调 上传成功 */
        fnUploadSuccess(resp, file, item) {
            item.img_url = resp.url;
            item.status = 'success';
        },
        fnUploadError(item){
            item.preview_url = '';
            item.status = 'fail';
        },
        fnUpload(e, item) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            item.uploadTime = timeTmp;
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if(item.uploadTime != timeTmp){
                        return ;
                    }
                    if (resp.code == 1) {
                        // 调用组件成功回调,修改样式
                        e.onSuccess(resp.data, {
                            url: resp.data.url
                        }, this.fileList);
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.image_url = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnReset(){
            this.$refs.mainform.resetFields();
        }
    }
};
</script>

<style lang="less" scoped>
    .avatar{
        width: 100%;
        height: 100%;;
    }
    .margin-top{
        margin-top: 15px;
    }
    .banner-add-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
    .el-select-title {
        display: inline-block;
        color: #909399;
        background: #F5F7FA;
        padding: 0 18px;
        border: 1px solid #DCDFE6;
        border-radius: 4px 0 0 4px;
        border-right: none;
        height: 32px;
        white-space: nowrap;
    }
    .el-icon-circle-plus-outline {
        font-size: 20px;
        line-height: 32px;
        align-items: center;
        color: #20a0ff;
        cursor: pointer;
    }
    .school-list {
        max-height: 310px;
        overflow: auto;
        .empty {
            text-align: center;
            color: #7e8993;
        }
    }
    .submit-btn {
        margin: 30px auto 0;
        display: block;
    }
    .el-tag-school {
        display: flex;
        width: 100%;
        flex-wrap: wrap;
        margin-bottom: 10px;
        .el-tag{
            margin-right: 10px;
            margin-bottom: 10px;
            height: 32px;
            display: flex;
            align-items: center;
        }
    }
</style>
<style lang="less">
.el-form .form-unit .row-flex .el-form-item__content .el-input__inner::-webkit-input-placeholder{
    color: #606266;
}
.banner-add-wrap {
    .el-checkbox-button {
      margin-right: 10px;
      margin-bottom: 10px;
      border-radius: 0;
    }
    .el-checkbox-button:first-child .el-checkbox-button__inner {
      border-radius: 2;
    }
    .el-checkbox-button__inner {
      border-left: 1px solid #dcdfe6;
      font-size: 12px;
      font-weight: 400;
      color: rgba(126, 137, 147, 1);
      border-radius: 2px;
      position: relative;
    }
    .el-checkbox-button.is-checked .el-checkbox-button__inner {
      background-color: #fff;
      border: 1px solid rgba(32, 160, 255, 1);
      color: #20a0ff;
      box-shadow: none;
      overflow: hidden;
      &::after {
        content: " ";
        position: absolute;
        bottom: 0;
        right: 0;
        width: 24px;
        height: 18px;
        background-image: url(//cdn.zsdx.cn/admin/images/common/checked.png);
        background-position: center;
        background-size: cover;
        background-repeat: no-repeat;
      }
    }
  }
</style>
